package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Base.GoodsInfo;
import com.ydkj.a37e_mall.Classes.Model.Request.EditShoppingCarReq;
import com.ydkj.a37e_mall.Classes.Model.Request.GetMallOrderReq;
import com.ydkj.a37e_mall.Classes.Model.Request.LoginReq;
import com.ydkj.a37e_mall.Classes.Model.Request.OauthloginReq;
import com.ydkj.a37e_mall.Classes.Model.Response.GetMallOrderResp;
import com.ydkj.a37e_mall.Classes.Model.Response.GetOrderResp;
import com.ydkj.a37e_mall.Classes.Model.Response.LoginResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_post;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.ListViewForScrollView;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;


/**
 * Created by hong on 2016/3/25.
 * <p>
 * 确认订单
 */
public class ConfirmationOrder extends AppCompatActivity implements View.OnClickListener {
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private ImageView img_back;
    private LinearLayout lly_accept_goods_address, lly_address_message;
    private TextView tv_receive_name, tv_phone_number, tv_address, tv_order_state,
            tv_total_numbers, tv_total_package, tv_total_price, tv_commit_order;
    private ListViewForScrollView lv_product_details;


    private ConfirmationAdapter confirmationAdapter;
    private String secret;
    private List<GetMallOrderResp.ResultEntity.DataEntity> orderSnList;
    private List<GoodsInfo> intentList;
    private List<LoginResp.ResultEntity.DataEntity.MemberAddressEntity> addressEntityList;
    private double all_price = 0.00;
    private int all_num = 0;
    private int address;
    private int numbers = 0;
    private String buy_number;
    private List<String> idList;
    private List<String> message;

    private String orderId;
    private String order_sn;
    private int order_size = 0, index = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.confirmation_order);
        mActivity = this;
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance().getInstance();


        if (!sharedPreferencesUtil.getOpen_id().equals("")) {
            Oauth_login();
        } else {
            AutoLogin();
        }
//        initWindow();//沉浸式状态栏
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);
    }

    private void init() {
        intentList = new ArrayList<GoodsInfo>();
        idList = new ArrayList<>();
        message = new ArrayList<>();

        if (intentList.size() != 0) {
            intentList.clear();
        }
        if (this.getIntent().getSerializableExtra("intentList") != null) {
            intentList = (ArrayList<GoodsInfo>) getIntent().getSerializableExtra("intentList");
            Log.e("ssss", "商品数量==》" + intentList.size());
            buy_number = getIntent().getStringExtra("buy_number");

            for (int i = 0; i < intentList.size(); i++) {
                idList.add(intentList.get(i).getId());
            }
            Log.e("url", "intentList_id==" + intentList.get(0).getProduct_id());
            Log.e("url", "intentList_name==" + intentList.get(0).getPrice());
            Log.e("url", "idList==" + idList.size());

        }
        lv_product_details = (ListViewForScrollView) mActivity.findViewById(R.id.lv_product_details);
        confirmationAdapter = new ConfirmationAdapter(intentList);
        lv_product_details.setAdapter(confirmationAdapter);


        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        lly_accept_goods_address = (LinearLayout) mActivity.findViewById(R.id.lly_accept_goods_address);
        lly_address_message = (LinearLayout) mActivity.findViewById(R.id.lly_address_message);
        tv_receive_name = (TextView) mActivity.findViewById(R.id.tv_receive_name);
        tv_phone_number = (TextView) mActivity.findViewById(R.id.tv_phone_number);
        tv_address = (TextView) mActivity.findViewById(R.id.tv_address);
        tv_order_state = (TextView) mActivity.findViewById(R.id.tv_order_state);
        tv_total_numbers = (TextView) mActivity.findViewById(R.id.tv_total_numbers);
        tv_total_package = (TextView) mActivity.findViewById(R.id.tv_total_package);
        tv_total_package.setText("(邮费到付)");
        tv_total_price = (TextView) mActivity.findViewById(R.id.tv_total_price);
        tv_commit_order = (TextView) mActivity.findViewById(R.id.tv_commit_order);


        if (address == 0) {
//            lly_address_message.setVisibility(View.GONE);
            tv_address.setText("请选择收货地址");
        } else {
            tv_receive_name.setText("收货人: " + addressEntityList.get(0).getName());
        }
        tv_phone_number.setText(addressEntityList.get(0).getMobile());
        tv_address.setText("  收货地址: " + addressEntityList.get(0).getDetail());


        //全部的商品数
        for (int i = 0; i < intentList.size(); i++) {
            numbers = numbers + Integer.parseInt(intentList.get(i).getNumbers());
        }
        tv_total_numbers.setText("共" + numbers + "件商品");

        //总价
        for (int i = 0; i < intentList.size(); i++) {
            all_price = all_price + Integer.parseInt(intentList.get(i).getNumbers()) * Double.parseDouble(intentList.get(i).getPrice());
            Log.e("url", "all_price=====" + all_price);
        }
        tv_total_price.setText(all_price + "");

        img_back.setOnClickListener(this);
        lly_accept_goods_address.setOnClickListener(this);
        tv_commit_order.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back://返回
                finish();
                break;
            case R.id.lly_accept_goods_address://收货地址
                Intent intent = new Intent(ConfirmationOrder.this, ChooseAddress.class);
                startActivityForResult(intent, 1);
                break;

            case R.id.tv_commit_order:
                Log.e("url", "all_price==" + all_price);
                if (all_price == 0.0) {
                    CommonUtil.showToast(mActivity, "商品数量为0");
                } else {
                    order_size = intentList.size();
                    GetOrder();

                }
                break;
        }
    }

    private class ConfirmationAdapter extends BaseAdapter {
        private List<GoodsInfo> confirmationOrderInfoList;

        private ConfirmationAdapter(List<GoodsInfo> infos) {
            if (infos == null) {
                infos = new ArrayList<GoodsInfo>();
            }
            confirmationOrderInfoList = infos;
        }

        @Override
        public int getCount() {
            return confirmationOrderInfoList.size();
        }

        /**
         * 获得某一位置的数据
         */
        @Override
        public GoodsInfo getItem(int position) {
            return confirmationOrderInfoList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.confirmation_order_listitem, null);
                vh = new ViewHolder();
                vh.img_thumb = (ImageView) convertView.findViewById(R.id.img_thumb);
                vh.tv_describe = (TextView) convertView.findViewById(R.id.tv_describe);
                vh.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
                vh.tv_postage = (TextView) convertView.findViewById(R.id.tv_postage);
                vh.tv_type_content = (TextView) convertView.findViewById(R.id.tv_type_content);
                vh.tv_num = (TextView) convertView.findViewById(R.id.tv_num);
                vh.tv_number_add = (TextView) convertView.findViewById(R.id.tv_number_add);
                vh.tv_number_less = (TextView) convertView.findViewById(R.id.tv_number_less);
                vh.et_buy_number = (EditText) convertView.findViewById(R.id.et_buy_number);
                vh.tv_product_title = (TextView) convertView.findViewById(R.id.tv_product_title);
                vh.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
                vh.et_to_saler_message = (EditText) convertView.findViewById(R.id.et_to_saler_message);
                vh.rly_product_details = (RelativeLayout) convertView.findViewById(R.id.rly_product_details);

                vh.et_to_saler_message.setTag(position);
                vh.et_to_saler_message.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            index = (Integer) v.getTag();
                        }
                        return false;
                    }
                });
                final ViewHolder mHolder = vh;
                class MyTextWatcher implements TextWatcher {
                    public MyTextWatcher(ViewHolder holder) {
                        mHolder = holder;
                    }

                    private ViewHolder mHolder;

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                                              int before, int count) {
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start,
                                                  int count, int after) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (s != null && !"".equals(s.toString())) {
                            int position = (Integer) mHolder.et_to_saler_message.getTag();
                            intentList.get(position).setMessage(s.toString());// 当EditText数据发生改变的时候存到data变量中
                        }
                    }
                }
                vh.et_to_saler_message.addTextChangedListener(new MyTextWatcher(vh));

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);

            vh.tv_product_title.setText(getItem(position).getExpress_method());

            vh.tv_describe.setText(getItem(position).getName());
            vh.tv_num.setText("x " + getItem(position).getNumbers() + "");
            vh.et_buy_number.setText(getItem(position).getNumbers() + "");
            vh.tv_type_content.setText(getItem(position).getList_title());
            ImageLoader.getInstance().displayImage(getItem(position).getThumb(), vh.img_thumb);
            vh.tv_price.setText("¥ " + getItem(position).getPrice());///////商品单价

            if (position == 0) {
                vh.tv_title.setVisibility(View.GONE);
            } else {
                vh.tv_title.setVisibility(View.VISIBLE);

            }

            //增加
            final ViewHolder finalVh = vh;
            vh.tv_number_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int i = Integer.parseInt(finalVh.et_buy_number.getText().toString().trim());
                    i++;
                    finalVh.et_buy_number.setText(i + "");
                    finalVh.tv_num.setText("x " + i + "");

                    all_num = all_num + i;
                    numbers++;
                    tv_total_numbers.setText("共" + numbers + "件商品");


                    all_price = all_price + Double.parseDouble(getItem(position).getNow_price() + "");
                    Log.e("ssss", "增加的价格==》" + all_price);
                    tv_total_price.setText(all_price + "");
                    EditShoppingCarListNumber(getItem(position).getId(), getItem(position).getProduct_id() + "", Integer.parseInt(finalVh.et_buy_number.getText().toString().trim()));

//    Log.e("url", "price==" + getItem(position).getProduct().getActivity_price());
                    // +"积分"     "¥" +
//                    if (getItem(position).getIs_integral() == 0) {//普通商品
//                        all_price = all_price + Double.parseDouble(getItem(position).getNow_price() + "");
//                        if (getItem(position).getProduct().getIntegral().equals("")) {
//                            all_integral = 0.00;
//                        } else {
//                            all_integral = all_integral + Double.parseDouble(getItem(position).getProduct().getIntegral());
//                        }
//                        tv_all_price.setText("¥" + all_price);
//                        tv_all_give_integral.setText("(赠送" + all_integral + "积分)");
//                        tv_total_price.setText("¥" + all_price);
//                        tv_total_give_integral.setText("(赠送" + all_integral + "积分)");
//                        tv_all_numbers.setText("共" + i + "件商品");
//                        tv_total_numbers.setText("共" + i + "件商品");
//                    } else {//积分商品
//                        all_price = all_price + Double.parseDouble(getItem(position).getNow_price() + "");
//                        tv_all_price.setText(all_price + "积分");
//                        tv_total_price.setText(all_price + "积分");
//                        tv_all_numbers.setText("共" + i + "件商品");
//                        tv_total_numbers.setText("共" + i + "件商品");
//                    }

                }
            });

            //减少
            vh.tv_number_less.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int i = Integer.parseInt(finalVh.et_buy_number.getText().toString().trim());
                    if (i == 1) {
                        return;
                    } else {
                        i--;
                        finalVh.et_buy_number.setText(i + "");
                        finalVh.tv_num.setText("x " + i + "");
//                        finalVh.tv_price.setText("¥ " + i * Double.parseDouble(getItem(position).getPrice()) + "");///////商品单价

                        all_num = all_num - Integer.parseInt(getItem(position).getNumbers());
                        numbers--;
                        tv_total_numbers.setText("共" + numbers + "件商品");

                        all_price = all_price - Double.parseDouble(getItem(position).getNow_price() + "");
                        Log.e("ssss", "减少的价格==》" + all_price);
                        tv_total_price.setText(all_price + "");

                        EditShoppingCarListNumber(getItem(position).getId(), getItem(position).getProduct_id() + "", Integer.parseInt(finalVh.et_buy_number.getText().toString().trim()));


//                        // +"积分"     "¥" +
//                        if (getItem(position).getIs_integral() == 0) {//普通商品
//                            all_price = all_price - Double.parseDouble(getItem(position).getNow_price() + "");
//                            if (getItem(position).getProduct().getIntegral().equals("")) {
//                                all_integral = 0.00;
//                            } else {
//                                all_integral = all_integral - Double.parseDouble(getItem(position).getProduct().getIntegral() + "");
//                            }
//                            tv_all_price.setText("¥" + all_price);
//                            tv_all_give_integral.setText("(赠送" + all_integral + "积分)");
//                            tv_total_price.setText("¥" + all_price);
//                            tv_total_give_integral.setText("(赠送" + all_integral + "积分)");
//                            tv_all_numbers.setText("共" + i + "件商品");
//                            tv_total_numbers.setText("共" + i + "件商品");
//                        } else {//积分商品
//                            all_price = all_price - Double.parseDouble(getItem(position).getNow_price() + "");
//                            tv_all_price.setText(all_price + "积分");
//                            tv_total_price.setText(all_price + "积分");
//                            tv_all_numbers.setText("共" + i + "件商品");
//                            tv_total_numbers.setText("共" + i + "件商品");
//                        }
                    }
                }
            });


            //商品数量输入
            vh.et_buy_number.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    Log.e("url", "actionId==" + actionId);

                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        all_price = actionId * Double.parseDouble(getItem(position).getNow_price() + "");
//                        tv_all_price.setText("¥" + all_price);
                        tv_total_price.setText("¥" + all_price);
                        Log.e("111", "111");
                        return true;
                    }
                    return false;
                }
            });

            vh.rly_product_details.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(ConfirmationOrder.this, DistributionMode.class);
                    intent.putExtra("product_id", getItem(position).getProduct_id());
                    intent.putExtra("position", position + "");
                    startActivityForResult(intent, 2);
                }
            });
            return convertView;
        }

        private class ViewHolder {
            public ImageView img_thumb;
            public TextView tv_describe, tv_price, tv_postage, tv_type_content, tv_num, tv_number_less,
                    tv_number_add, tv_title, tv_product_title;
            public EditText et_buy_number, et_to_saler_message;
            public RelativeLayout rly_product_details;
        }
    }

    //自动登录
    private void AutoLogin() {
        Log.e("ssss1", "账号密码登录==>");
//        CustomProgressDialog.createDialog(mActivity).Show();


        LoginReq req = new LoginReq();
        req.setMobile(sharedPreferencesUtil.getUsername());
        req.setPassword(sharedPreferencesUtil.getPassword());
        req.setDevice_type(3);
        if (!myApplication.getChannelID().equals("")) {
            req.setAlias(myApplication.getChannelID());
        }
        String url = Const.COMMON_ADDRESS + req.urlString();
        RequestParams params = new RequestParams();
        params.put("mobile", req.getMobile());
        params.put("password", req.getPassword());
//        params.put("channel_id", req.getChannel_id());
        params.put("device_type", req.getDevice_type());
        try {
            String source = req.getString();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("secret", secret);
        Log.e("url", "parems==" + params);
        Async_http_post.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                addressEntityList = new ArrayList<LoginResp.ResultEntity.DataEntity.MemberAddressEntity>();
//                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    Log.e("url", "AutoLogin_json==" + response);
                    LoginResp resp = GsonImpl.get().toObject(response.toString(), LoginResp.class);
                    sharedPreferencesUtil.setAccessToken(resp.getResult().getAccess_token());
                    myApplication.setDataEntity(resp.getResult().getData());
                    addressEntityList.clear();
                    addressEntityList.add(resp.getResult().getData().getMember_address());
                    for (int i = 0; i < addressEntityList.size(); i++) {
                        Log.e("ssss", "addressEntityList==>" + addressEntityList.get(i).getProvince());

                    }
                    address = addressEntityList.get(0).getId();
                    init();
                }
                if (!errno.equals("000")) {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    //第三方登录
    private void Oauth_login() {
        Log.e("ssss1", "第三方登录==>");
//        CustomProgressDialog.createDialog(mActivity).show();
        OauthloginReq req = new OauthloginReq();
        req.setOpenid(sharedPreferencesUtil.getOpen_id());
        req.setType(sharedPreferencesUtil.getType() + "");
        req.setAlias(myApplication.getChannelID());
        req.setDevice_type("3");
        req.setNickname(sharedPreferencesUtil.getNickname());
        req.setAvatar(sharedPreferencesUtil.getAvatar());
        RequestParams params = new RequestParams();
        params.put("secret", req.getSecret());

        Async_http_post.post(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                addressEntityList = new ArrayList<LoginResp.ResultEntity.DataEntity.MemberAddressEntity>();

//                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmag = response.optString("errmsg");
                Log.e("url", "第三方==" + response);
                if (errno.equals("000")) {
                    LoginResp resp = GsonImpl.get().toObject(response.toString(), LoginResp.class);
                    sharedPreferencesUtil.setAccessToken(resp.getResult().getAccess_token());
                    myApplication.setDataEntity(resp.getResult().getData());
                    addressEntityList.clear();
                    addressEntityList.add(resp.getResult().getData().getMember_address());
                    for (int i = 0; i < addressEntityList.size(); i++) {
                        Log.e("ssss", "addressEntityList==>" + addressEntityList.get(i).getProvince());

                    }
                    address = addressEntityList.get(0).getId();
                    init();
                }
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });

    }

    //修改购物车（更改商品数目）
    private void EditShoppingCarListNumber(final String id, final String product_id, int number) {
        Log.e("ssss", "id==>" + id);
        Log.e("ssss", "product_id==>" + product_id);
        CustomProgressDialog.createDialog(mActivity).Show();
        EditShoppingCarReq req = new EditShoppingCarReq();
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setProduct_id(product_id);
        req.setNum(number + "");

        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Log.e("ssss", "idididid==>" + id);
        Log.e("ssss", "secret==>" + req.getSecret());

        AsyncHttpClient client = new AsyncHttpClient();
        client.put(Const.COMMON_ADDRESS + req.urlString() + id, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("url", "editshoppingcar_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");

                if (errno.equals("000")) {
//                    GetShoppingCarList(REFRESH);
//                    shoppingWholesaleCarListAdapter.notifyDataSetChanged();
                } else if (errno.equals("999")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 2);
                } else if (errno.equals("888")) {
                    CommonUtil.showToast(mActivity, errmsg);
//                    GetShoppingCarList(REFRESH);
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                    confirmationAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接错误");
            }
        });
    }

//    //获取是否包邮
//    private void GetFreeShipping() {
//        StringBuffer buffer = new StringBuffer();
//        for (int i = 0; i < idList.size(); i++) {
//            if (i == idList.size() - 1) {
//                buffer.append(idList.get(i));
//            } else {
//                buffer.append(idList.get(i) + ",");
//            }
//        }
//
//        FreeShippingReq req = new FreeShippingReq();
//        req.setId(buffer.toString());
//        try {
//            String source = req.getString();
//            Rsa rsa = new Rsa();
//            secret = rsa.encryptByPublic(source);
//            Log.e("url", "source==" + source);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        String url = Const.COMMON_ADDRESS + req.urlString();
//        RequestParams params = new RequestParams();
//        params.put("id", req.getId());
//        params.put("secret", secret);
//        Log.e("url", "params==" + params);
//
//        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//                super.onSuccess(statusCode, headers, response);
//                Log.e("url", "free_shoppingcar_json==" + response);
//                String errno = response.optString("errno");
//                String errmsg = response.optString("errmsg");
//                Log.e("url", "errmsg==" + errmsg);
//
//                tv_total_package.setText("(" + errmsg + ")");
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                super.onFailure(statusCode, headers, responseString, throwable);
//                CustomProgressDialog.Dismiss();
//                CommonUtil.showToast(mActivity, "网络连接错误");
//            }
//        });
//    }

    //提交订单(新增订单)
    private void GetOrder() {
        if (address == 0) {
            CommonUtil.showToast(mActivity, "请选择收货地址");
            return;
        }

        Log.e("url", "intentList.size()==" + intentList.size());
        for (int i = 0; i < intentList.size(); i++) {
            Log.e("url", "message==" + intentList.get(i).getMessage());
        }

        //uuid=当前登录用户&message=给卖家的留言&cart_id=购物车编号
        // &address_id=收货地址编号&store_id=门店编号&delivery_type=配送方式(1为快递配送,2为门店自提)的RSA加密字符串

        if (index == order_size) {


            Intent intent = new Intent(ConfirmationOrder.this, PayMoney.class);
            Log.e("ssss", "订单编号==》" + order_sn);
            Log.e("ssss", "订单id==》" + orderId);
            Log.e("ssss", "订单总价==》" + all_price);
            intent.putExtra("order_price", all_price + "");
            intent.putExtra("order_id", orderId);
            intent.putExtra("order_sn", order_sn);
            startActivity(intent);

        } else {
            if (index == 0) {
                CustomProgressDialog.createDialog(mActivity).Show();
            }

            GetMallOrderReq req = new GetMallOrderReq();
//            StringBuffer buffer = new StringBuffer();
//            for (int i = 0; i < intentList.size(); i++) {
//                if (i == intentList.size() - 1) {
//                    buffer.append(intentList.get(i).getId());
//                } else {
//                    buffer.append(intentList.get(i).getId() + ",");
//                }
//            }

            req.setUuid(myApplication.getDataEntity().getUuid());
            if (intentList.get(index).getMessage() != null) {
                req.setMessage(intentList.get(index).getMessage());
            }
            req.setCart_id(intentList.get(index).getId() + "");
            req.setNumber(intentList.get(index).getNumbers() + "");
            req.setAddress_id(address + "");
            if (intentList.get(index).getStore_id().equals("0")) {
                req.setStore_id(intentList.get(index).getStore_id());
                req.setDelivery_type("1");
            } else {
                req.setStore_id(intentList.get(index).getStore_id());
                req.setDelivery_type("2");
            }

            try {
                Rsa rsa = new Rsa();
                String source = null;
                if (intentList.get(index).getMessage() == null) {//无留言
                    source = req.getString();
                } else {
                    source = req.getString2();
                }
                secret = rsa.encryptByPublic(source);
                Log.e("url", "source==" + source);
            } catch (Exception e) {
                e.printStackTrace();
            }
            RequestParams params = new RequestParams();
            params.put("token", sharedPreferencesUtil.getAccessToken());
            params.put("secret", secret);
            Log.e("url", "sharedPreferencesUtil.getAccessToken()==" + sharedPreferencesUtil.getAccessToken());
            String url = Const.COMMON_ADDRESS + req.urlString();
            Async_http_post.post(url, params, new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    super.onSuccess(statusCode, headers, response);
                    CustomProgressDialog.Dismiss();
                    String errno = response.optString("errno");
                    String errmsg = response.optString("errmsg");
                    Log.e("url", "commit_orser_json==" + response.toString());
                    if (errno.equals("000")) {
                        GetOrderResp resp = GsonImpl.get().toObject(response.toString(), GetOrderResp.class);

                        orderId = resp.getResult().getData().getId();
                        order_sn = resp.getResult().getData().getSn();

                        index++;
                        GetOrder();
//                        orderSnList = new ArrayList<GetMallOrderResp.ResultEntity.DataEntity>();
//                        orderSnList.add(resp.getResult().getData());
//                    if (!et_to_saler_message.getText().toString().equals("")) {
//                        Message();
//                    }
//                    if (intentList.get(0).getIs_integral() == 0) {//普通订单支付
//                        Intent intent = new Intent(ConfirmationOrder.this, PayMoney.class);
//                        intent.putExtra("order_id", orderSnList.get(0).getOrder_id());
//                        intent.putExtra("order_sn", orderSnList.get(0).getOrder_sn());
//                        intent.putExtra("invoice", (Integer) img_open_invoice.getTag());
//                        intent.putExtra("all_price", all_price + "");
//                        Log.e("ssss", "订单的钱==" + all_price);
//                        startActivity(intent);
//                        finish();
//                    } else {//积分订单支付
////                        IntegralOrderPay();
//                    }
                    } else if (errno.equals("999")) {
                        CommonUtil.showToast(mActivity, errmsg);
                        Intent intent = new Intent(mActivity, LoginActivity.class);
                        startActivityForResult(intent, 3);
                        Log.e("url", "errmsg==" + errmsg);
                    } else {
                        CommonUtil.showToast(mActivity, errmsg);
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    super.onFailure(statusCode, headers, responseString, throwable);
                    CustomProgressDialog.Dismiss();
                    CommonUtil.showToast(mActivity, "网络连接失败");
                }
            });

        }

    }

    //积分订单付款
//    private void IntegralOrderPay() {
//        OrderPayReq req = new OrderPayReq();
//        req.setId(orderSnList.get(0).getOrder_id());
//        req.setInvoice((Integer) img_open_invoice.getTag());
//        req.setType(4);
//        req.setAccess_token(sharedPreferencesUtil.getAccessToken());
//        try {
//            String source = req.getString();
//            Rsa rsa = new Rsa();
//            secret = rsa.encryptByPublic(source);
//            Log.e("url", "source==" + source);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        String url = Const.COMMON_ADDRESS + req.urlString();
//        RequestParams params = new RequestParams();
//        params.put("id", req.getId());
//        params.put("invoice", req.getInvoice());
//        params.put("type", req.getType());
//        params.put("access_token", req.getAccess_token());
//        params.put("secret", secret);
//        Log.e("url", "params==" + params);
//        Async_http_post.post(url, params, new JsonHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//                super.onSuccess(statusCode, headers, response);
//                CustomProgressDialog.Dismiss();
//                Log.e("url", "IntegralOrderPay_json==" + response.toString());
//                String errno = response.optString("errno");
//                String errmsg = response.optString("errmsg");
//                Log.e("ssss", "errno==>" + errno);
//                Log.e("ssss", "errmsg==>" + errmsg);
//                if (errno.equals("000")) {
//                    CommonUtil.showToast(mActivity, errmsg);
//                    finish();
//                } else if (errno.equals("999")) {
//                    CommonUtil.showToast(mActivity, errmsg);
//                    Intent intent = new Intent(mActivity, LoginActivity.class);
//                    startActivityForResult(intent, 3);
//                    Log.e("url", "errmsg==" + errmsg);
//                } else {
//                    CommonUtil.showToast(mActivity, errmsg);
//                }
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                CommonUtil.showToast(mActivity, "网络连接失败");
//            }
//        });
//    }
//
//    //留言、是否开具发票
//    private void Message() {
//        CustomProgressDialog.createDialog(mActivity).Show();
//        LeaveMessageReq req = new LeaveMessageReq();
//        req.setId(orderSnList.get(0).getOrder_id());
//        req.setAccess_token(sharedPreferencesUtil.getAccessToken());
//        if (!et_to_saler_message.getText().toString().equals("")) {
//            req.setMessage(et_to_saler_message.getText().toString());
//        } else {
//            req.setMessage("");
//        }
//
//        if (!et_invoice_header.equals("")) {
//            req.setInvoice_header(et_invoice_header.getText().toString());
//        } else {
//            req.setInvoice_header("");
//        }
//
//        try {
//            String source = req.getString();
//            Rsa rsa = new Rsa();
//            secret = rsa.encryptByPublic(source);
//            Log.e("url", "source==" + source);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        RequestParams params = new RequestParams();
//        params.put("id", req.getId());
//        params.put("access_token", req.getAccess_token());
//        params.put("message", req.getMessage());
//        params.put("invoice_header", req.getInvoice_header());
//        params.put("secret", secret);
//        Log.e("url", "params==" + params);
//        String url = Const.COMMON_ADDRESS + req.urlString();
//        Async_http_post.post(url, params, new JsonHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//                super.onSuccess(statusCode, headers, response);
//                CustomProgressDialog.Dismiss();
//                Log.e("url", "message_json==" + response.toString());
//                String errno = response.optString("errno");
//                String errmsg = response.optString("errmsg");
//                if (errno.equals("000")) {
////                    CommonUtil.showToast(mActivity, errmsg);
//                } else if (errno.equals("999")) {
//                    CommonUtil.showToast(mActivity, errmsg);
//                    Intent intent = new Intent(mActivity, LoginActivity.class);
//                    startActivityForResult(intent, 3);
//                    Log.e("url", "errmsg==" + errmsg);
//                }
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                super.onFailure(statusCode, headers, responseString, throwable);
//                CustomProgressDialog.Dismiss();
//                CommonUtil.showToast(mActivity, "网络连接失败");
//            }
//        });
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == Activity.RESULT_OK) {
                    tv_receive_name.setText(data.getExtras().getString("name"));
                    tv_phone_number.setText(data.getExtras().getString("mobile"));
                    tv_address.setText(data.getExtras().getString("detail"));
                    address = data.getExtras().getInt("id");
                }
                break;
            case 2:
                if (resultCode == Activity.RESULT_OK) {
                    //delivery_type=配送方式(1为快递配送,2为门店自提)
                    String delivery_type = data.getExtras().getString("delivery_type");
                    String store_id = data.getExtras().getString("store_id");
                    String name = data.getExtras().getString("name");
                    Log.e("url", "position==" + data.getExtras().getString("position"));
                    int position = Integer.parseInt(data.getExtras().getString("position"));
                    GoodsInfo goodsInfo = intentList.get(position);
                    goodsInfo.setExpress_method(name);
                    goodsInfo.setStore_id(store_id);
                    confirmationAdapter.notifyDataSetChanged();

                    Log.e("url", "delivery_type==" + data.getExtras().getString("delivery_type") + "  store_id==" + store_id + "  name==" + name + " position==" + position);
                }
                break;
            case 3:
                if (resultCode == Activity.RESULT_OK) {
                    GetOrder();
                }
                break;
        }
    }
}
